package com.wangwen.wechatmp.wxpkg.controller;


import com.google.common.collect.Maps;
import com.wangwen.wechatmp.dao.ConfWxmpDao;
import com.wangwen.wechatmp.entity.ApiResponse;
import com.wangwen.wechatmp.exception.RuntimeCheck;
import com.wangwen.wechatmp.model.ConfWxmp;
import com.wangwen.wechatmp.utils.WechatUtils;
import com.wangwen.wechatmp.wxpkg.config.WxMpConfiguration;
import com.wangwen.wechatmp.exception.RuntimeCheck;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 微信消息服务  微信推送的数据经过这里路由
 * @author wangwei
 *
 */
@Controller
@RequestMapping("wechat/message/{id}")
public class WxChatController {

	private final Logger logger = LoggerFactory.getLogger("access_info");


	@Autowired
	private WechatUtils wechatUtils;
	@Autowired
	private ConfWxmpDao confWxmpDao;

	/**
	 * 微信服务器认证
	 * @param signature
	 * @param timestamp
	 * @param nonce
	 * @param echostr
	 * @return
	 */
	@GetMapping(produces = "text/plain;charset=utf-8")
	@ResponseBody
	public String authGet(@PathVariable Integer id,@RequestParam(name = "signature", required = false) String signature,
			@RequestParam(name = "timestamp", required = false) String timestamp,
			@RequestParam(name = "nonce", required = false) String nonce,
			@RequestParam(name = "echostr", required = false) String echostr) {
		WxMpService wxMpService = wechatUtils.getMpService(id);
		if (StringUtils.isNoneEmpty(signature, timestamp, nonce, echostr)){
			if (wxMpService.checkSignature(timestamp, nonce, signature)) {
				this.logger.info("\n接收到来自微信服务器的认证消息：signature = [{}], timestamp = [{}], nonce = [{}], echostr = [{}]", signature, timestamp, nonce, echostr);

				return echostr;
			}
		}

		return "非法请求";
	}


	@PostMapping(produces = "application/xml; charset=UTF-8")
	@ResponseBody
	public String post(@PathVariable Integer id,@RequestBody String requestBody, @RequestParam("signature") String signature,
			@RequestParam("timestamp") String timestamp, @RequestParam("nonce") String nonce) {
		this.logger.info("\n接收微信请求：[signature=[{}], timestamp=[{}], nonce=[{}], requestBody=[\n{}\n] ", signature,
				timestamp, nonce, requestBody);
		//测试的时候，使用明文接收，暂时不需要解密
//		WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(requestBody, this.wxService.getWxMpConfigStorage(),
//				timestamp, nonce, signature);
//		this.logger.debug("\n消息解密后内容为：\n{} ", inMessage.toString());
		//明文内容传输    秘文模式可选择 ，可在微信公众号后台配置
		WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(requestBody);
		this.logger.debug("\n消息解密后内容为：\n{} ", inMessage.toString());
		System.out.println("----------------------");
		// 读取业务id 匹配的公众号信息
		ConfWxmp confWxmp = confWxmpDao.findByBusId(id);
		RuntimeCheck.ifNull(confWxmp,"该公众号信息未配置");
		WxMpService wxMpService = wechatUtils.getMpService(id);
		WxMpXmlOutMessage outMessage = this.route(id,confWxmp.getAppId(),inMessage,wxMpService);
		if (outMessage == null) {
			return "";
		}

		this.logger.debug("\n发送内容明文：\n{} ", outMessage.toString());
		String out = outMessage.toXml();
		this.logger.debug("\n组装回复信息：{}", out);
		return out;
	}


	private WxMpXmlOutMessage route(Integer busId,String appId,WxMpXmlMessage message,WxMpService wxMpService) {
		try {
			Map map = Maps.newConcurrentMap();
			map.put("busId",busId);
			return WxMpConfiguration.getRouters().get(appId).route(message,map,wxMpService);
		} catch (Exception e) {
			this.logger.error(e.getMessage(), e);
		}

		return null;
	}

}
